//
//  Requester.m
//  20240823
//
//  Created by 张伟 on 2024/8/23.
//

#import "Requester.h"

static NSString * const BaseUrl = @"http://120.26.251.180:2025/";

@interface Requester ()

@property (nonatomic) AFHTTPSessionManager * manager;

@end

@implementation Requester

+ (instancetype)shared{
    static Requester * obj = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        obj = Requester.new;
    });
    return obj;
}


/// 发送请求
/// - Parameters:
///   - api: api对象
///   - success: 成功回调
///   - error: 失败回调
- (void)sendRequest:(Apis *)api successHandle:(void (^)(ResultData * _Nonnull))success failHandle:(void (^)(NSString * _Nonnull))error {
    if (api.method == RequestMethodGet) {
        [self getRequest:api successHandle:success failHandle:error];
    }else{
        [self postRequest:api successHandle:success failHandle:error];
    }
}


/// get请求
/// - Parameters:
///   - api: api对象
///   - success: 成功回调
///   - error: 失败回调
-(void)getRequest:(Apis *)api successHandle:(void (^)(ResultData * _Nonnull))success failHandle:(void (^)(NSString * _Nonnull))error {
    
    [self.manager GET:[BaseUrl stringByAppendingString:api.path] parameters:api.parame headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        ResultData * data = [ResultData mj_objectWithKeyValues:responseObject];
        if (data.code == 200) {
            success(data);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull err) {
        error(err.description);
    }];
    
}


/// post请求
/// - Parameters:
///   - api: api对象
///   - success: 成功回调
///   - error: 失败回调
-(void)postRequest:(Apis *)api successHandle:(void (^)(ResultData * _Nonnull))success failHandle:(void (^)(NSString * _Nonnull))error {
    
    [self.manager POST:[BaseUrl stringByAppendingString:api.path] parameters:api.parame headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        ResultData * data = [ResultData mj_objectWithKeyValues:responseObject];
        if (data.code == 200) {
            if (success) {
                success(data);
            }
        }else{
            [ZWHud showMessage:data.msg finishHandle:nil];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull err) {
        [ZWHud showMessage:[err.localizedDescription stringByAppendingFormat:@"%ld",err.code] finishHandle:nil];
        if (error) {
            error(err.description);
        }
    }];
    
}

//配置请求对象
- (AFHTTPSessionManager *)manager {
    if (_manager == nil) {
        _manager = [AFHTTPSessionManager manager];
        _manager.requestSerializer = [AFJSONRequestSerializer serializer]; // 确保请求体是JSON格式
        [_manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    }
    return _manager;
}


@end
